package com.ruoyi.web.controller.social.examine;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.resp.ExamineRecordDTO;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/9/7
 **/
@RestController
@RequestMapping("/social/examine/record")
public class ExamineRecordController extends BaseController {
    @Resource
    private ExamineRecordService examineRecordService;

    @Resource
    private ExamineRecordDetailService examineRecordDetailService;

    @Resource
    private ExaminePlanService examinePlanService;

    @Resource
    private CompanyService companyService;

    @Resource
    private ExaminePlanDetailService examinePlanDetailService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserPostMapper sysUserPostMapper;

    @Resource
    private ApproveService approveService;

    @Log(title = "查询考核记录", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(ExamineRecord examineRecord) {
//        Long userId = SecurityUtils.getUserId();
//        SysUser sysUser = sysUserMapper.selectUserById(userId);
//        List<Long> postIds = sysUserPostMapper.getUserPosts(SecurityUtils.getUserId());
//        if (CollectionUtils.isEmpty(postIds)) {
//            // 默认只能看到自己的数据
//            examineRecord.setCreator(userId);
//            examineRecord.setDept(null);
//        } else if (postIds.stream().anyMatch(p -> p < 7)) {
//            // 副主任以上能看到所有数据
//            examineRecord.setCreator(null);
//            examineRecord.setDept(null);
//        } else if (postIds.stream().anyMatch(p -> p <= 8 && p >= 7)) {
//            // 科长副科长只能看到自己科室的数据
//            examineRecord.setCreator(null);
//            examineRecord.setDept(sysUser.getDeptId());
//        } else {
//            // 其他人只能看到自己科室的自己的数据
//            examineRecord.setCreator(userId);
//            examineRecord.setDept(sysUser.getDeptId());
//        }
        startPage();
        List<ExamineRecord> list = examineRecordService.selectList(examineRecord);
        return getDataTable(fillToDTO(list));
    }

    @Log(title = "查询考核所有公司", businessType = BusinessType.OTHER)
    @GetMapping("/companyList")
    public AjaxResult companyList(ExamineRecord examineRecord) {
//        startPage();
        List<ExamineRecord> list = examineRecordService.companyList(examineRecord);
        return AjaxResult.success();
//        return getDataTable(fillToDTO(list));
    }

    @GetMapping("/getScore")
    public AjaxResult getScore(ExamineRecord examineRecord) {
        Score score = new Score();
         List<ExamineRecord> list = examineRecordService.selectList(examineRecord);
        List<ExamineRecordDTO> lvhua = new ArrayList<>();
        List<ExamineRecordDTO> anbao = new ArrayList<>();
        List<ExamineRecordDTO> baojie = new ArrayList<>();

        List<ExamineRecordDTO> dtos = fillToDTO(list);
        if (!CollectionUtils.isEmpty(dtos)) {
            for (ExamineRecordDTO dto : dtos) {
                if (StringUtils.isNotBlank(dto.getApproveStatus()) && dto.getApproveStatus().equals("通过")) {
                    if (StringUtils.isNotBlank(dto.getCompanyType()) && dto.getCompanyType().equals("绿化养护服务")) {
                        lvhua.add(dto);
                    }
                    if (StringUtils.isNotBlank(dto.getCompanyType()) && dto.getCompanyType().equals("保洁服务")) {
                        baojie.add(dto);
                    }
                    if (StringUtils.isNotBlank(dto.getCompanyType()) && dto.getCompanyType().equals("安保公司")) {
                        anbao.add(dto);
                    }
                }
            }
        }

        if (!CollectionUtils.isEmpty(lvhua)) {
            ExamineRecordDTO examineRecordDTO = lvhua.stream().sorted(Comparator.comparing(BaseEntity::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
            score.setLvhua(examineRecordDTO.getTotal() == null ? BigDecimal.ZERO : examineRecordDTO.getTotal());
            //            for (ExamineRecordDTO examineRecordDTO : lvhua) {
//                score.setLvhua(score.getLvhua().add(examineRecordDTO.getTotal() == null ? BigDecimal.ZERO : examineRecordDTO.getTotal()));
//            }
        }
        if (!CollectionUtils.isEmpty(anbao)) {
            ExamineRecordDTO examineRecordDTO = anbao.stream().sorted(Comparator.comparing(BaseEntity::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
            score.setAnbao(examineRecordDTO.getTotal() == null ? BigDecimal.ZERO : examineRecordDTO.getTotal());
//            for (ExamineRecordDTO examineRecordDTO : anbao) {
//                score.setAnbao(score.getAnbao().add(examineRecordDTO.getTotal() == null ? BigDecimal.ZERO : examineRecordDTO.getTotal()));
//            }
        }
        if (!CollectionUtils.isEmpty(baojie)) {
            ExamineRecordDTO examineRecordDTO = baojie.stream().sorted(Comparator.comparing(BaseEntity::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
            score.setBaojie(examineRecordDTO.getTotal() == null ? BigDecimal.ZERO : examineRecordDTO.getTotal());
//            for (ExamineRecordDTO examineRecordDTO : anbao) {
//                score.setAnbao(score.getAnbao().add(examineRecordDTO.getTotal() == null ? BigDecimal.ZERO : examineRecordDTO.getTotal()));
//            }
        }
        score.setTotal(score.getAnbao().add(score.getLvhua()));
        return AjaxResult.success(score);
    }


    @Log(title = "查询考核记录All", businessType = BusinessType.OTHER)
    @GetMapping("/listAll")
    public TableDataInfo listAll(ExamineRecord examineRecord) {
        List<ExamineRecord> list = examineRecordService.selectList(examineRecord);
        return getDataTable(fillToDTO(list));
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(fillSingleToDTO(examineRecordService.selectById(id)));
    }

    @Log(title = "添加考核记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody ExamineRecord examineRecord) {
        Long userId = SecurityUtils.getUserId();
        examineRecord.setCreator(userId);
        examineRecord.setDept(Optional.ofNullable(sysUserMapper.selectUserById(userId)).map(SysUser::getDeptId).orElse(null));
        examineRecord.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = examineRecordService.create(examineRecord);
        if (!result) {
            return error("插入失败");
        }
        ExaminePlan examinePlan = examinePlanService.selectById(examineRecord.getPlanId());
        if (examinePlan == null) {
            return error("没有这个方案");
        }
        List<ExaminePlanDetail> examinePlanDetails = examinePlanDetailService.selectList((ExaminePlanDetail.builder().planId(examineRecord.getPlanId()).build()));
        if (CollectionUtils.isEmpty(examinePlanDetails)) {
            return success();
        }
        examinePlanDetails.forEach(e -> {
            ExamineRecordDetail examineRecordDetail = new ExamineRecordDetail();
            examineRecordDetail.setRecordId(examineRecord.getId());
            examineRecordDetail.setBig(e.getBig());
            examineRecordDetail.setSmall(e.getSmall());
            examineRecordDetail.setStandard(e.getStandard());
            examineRecordDetail.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            examineRecordDetailService.create(examineRecordDetail);
        });
        return success();
    }

    @Log(title = "修改考核记录", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@Validated @RequestBody ExamineRecord examineRecord) {
        examineRecord.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = examineRecordService.update(examineRecord);

        ExamineRecord search = examineRecordService.selectById(examineRecord.getId());
        if (search == null || !search.getCreateBy().equals(SecurityUtils.getLoginUser().getUser().getNickName())) {
            throw new BaseException("该单据由" + search.getCreateBy() + "创建，您无法修改");
        }

        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "删除考核记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        ExamineRecord search = examineRecordService.selectById(id);
        if (search == null || !search.getCreateBy().equals(SecurityUtils.getLoginUser().getUser().getNickName())) {
            throw new BaseException("该单据由" + search.getCreateBy() + "创建，您无法删除");
        }
        return toAjax(examineRecordService.deleteById(id));
    }

    private List<ExamineRecordDTO> fillToDTO(List<ExamineRecord> examineRecords) {
        if (CollectionUtils.isEmpty(examineRecords)) {
            return Collections.emptyList();
        }
        PageInfo<ExamineRecord> oldPage = new PageInfo<>(examineRecords);
        Page<ExamineRecordDTO> newPage = new Page<>();
        newPage.setTotal(oldPage.getTotal());

        List<Long> planIds = examineRecords.stream().map(ExamineRecord::getPlanId).collect(Collectors.toList());
        List<ExaminePlan> examinePlans = examinePlanService.selectByIds(planIds);
        Map<Long, ExaminePlan> examinePlanMap;
        if (!CollectionUtils.isEmpty(examinePlans)) {
            examinePlanMap = examinePlans.stream().collect(Collectors.toMap(ExaminePlan::getId, e -> e));
        } else {
            examinePlanMap = new HashMap<>();
        }

        List<ExamineRecordDTO> examineRecordDTOS = examineRecords.stream().map(e -> {
            ExamineRecordDTO examineRecordDTO = new ExamineRecordDTO();
            examineRecordDTO.setId(e.getId());
            examineRecordDTO.setExaminePeople(e.getExaminePeople());
            examineRecordDTO.setTime(e.getTime());
            examineRecordDTO.setPlanId(e.getPlanId());
            examineRecordDTO.setCompanyName(e.getCompanyName());
            examineRecordDTO.setCreateBy(e.getCreateBy());
            examineRecordDTO.setCreateTime(e.getCreateTime());
            examineRecordDTO.setUpdateBy(e.getUpdateBy());
            examineRecordDTO.setUpdateTime(e.getUpdateTime());
            examineRecordDTO.setRemark(e.getRemark());
            examineRecordDTO.setPlanName(Optional.ofNullable(examinePlanMap.get(e.getPlanId())).map(ExaminePlan::getName).orElse(null));
            List<ExamineRecordDetail> details = examineRecordDetailService.selectList(ExamineRecordDetail.builder().recordId(e.getId()).build());
            if (CollectionUtils.isEmpty(details)) {
                examineRecordDTO.setTotal(new BigDecimal(100));
            } else {
                List<BigDecimal> scores = details.stream()
                        .map(ExamineRecordDetail::getScore)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                BigDecimal total = new BigDecimal(100);
                for (BigDecimal score : scores) {
                    total = total.subtract(score);
                }
                examineRecordDTO.setTotal(total);
            }
            ApproveMission approveMission = approveService.getApproveMissionByActivityd(e.getId(), "考核记录审批");
            examineRecordDTO.setApproveStatus(Optional.ofNullable(approveMission).map(ApproveMission::getStatus).orElse("未提交审批"));
            examineRecordDTO.setApproveMissionId(Optional.ofNullable(approveMission).map(ApproveMission::getId).orElse(null));

            String type = companyService.getTypeByName(examineRecordDTO.getCompanyName());
            examineRecordDTO.setCompanyType(type);
            return examineRecordDTO;
        }).collect(Collectors.toList());
        newPage.addAll(examineRecordDTOS);
        return newPage;
    }

    private ExamineRecordDTO fillSingleToDTO(ExamineRecord examineRecord) {
        if (examineRecord == null) {
            return null;
        }
        ExaminePlan examinePlan = examinePlanService.selectById(examineRecord.getPlanId());
        ExamineRecordDTO examineRecordDTO = new ExamineRecordDTO();
        examineRecordDTO.setId(examineRecord.getId());
        examineRecordDTO.setExaminePeople(examineRecord.getExaminePeople());
        examineRecordDTO.setTime(examineRecord.getTime());
        examineRecordDTO.setPlanId(examineRecord.getPlanId());
        examineRecordDTO.setCompanyName(examineRecord.getCompanyName());
        examineRecordDTO.setCreateBy(examineRecord.getCreateBy());
        examineRecordDTO.setCreateTime(examineRecord.getCreateTime());
        examineRecordDTO.setUpdateBy(examineRecord.getUpdateBy());
        examineRecordDTO.setUpdateTime(examineRecord.getUpdateTime());
        examineRecordDTO.setRemark(examineRecord.getRemark());
        examineRecordDTO.setPlanName(Optional.ofNullable(examinePlan).map(ExaminePlan::getName).orElse(null));
        return examineRecordDTO;
    }
}
